﻿using Common.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using System.Security.Claims;
using Wallpaper.Data.Context;

namespace Wallpaper.Authorization.Handlers
{
    public class PermissionHandler : AuthorizationHandler<PermissionRequirement>
    {
        private readonly WallpaperDbContext _dbContext;
        private readonly string _superAdminRole;

        public PermissionHandler(
            WallpaperDbContext dbContext,
            IOptions<AuthorizationSettings> authorizationOptions)
        {
            _dbContext = dbContext;
            _superAdminRole = authorizationOptions.Value.SuperAdminRole ?? "super_admin"; ;
        }

        protected override async Task HandleRequirementAsync(
            AuthorizationHandlerContext context,
            PermissionRequirement requirement)
        {
            
            // 从 token 中取出 type 和 role
            var type = context.User.FindFirst("type")?.Value;
            var roleCode = context.User.FindFirst(ClaimTypes.Role)?.Value
               ?? context.User.FindFirst("role")?.Value;

            // 如果 type 是 user，直接放行
            if (type == "user")
            {
                context.Succeed(requirement); // ✅ 认证成功，放行
                return;
            }

            // 如果不是 user，继续检查角色
            if (string.IsNullOrEmpty(roleCode))
            {
                context.Fail(); // ❌ 既不是user也没有角色，认证失败
                return;
            }

            // ✅ 从配置获取超级管理员角色
            if (IsSuperAdmin(roleCode))
            {
                context.Succeed(requirement);
                return;
            }

            // 查角色对应的权限码
            var hasPermission = await _dbContext.Roles
                .Where(r => r.RoleCode == roleCode)
                .SelectMany(r => r.RolePermissions)
                .Include(rp => rp.Permission)
                .AnyAsync(rp => rp.Permission.Code == requirement.PermissionCode);

            if (hasPermission)
                context.Succeed(requirement);
            else
                context.Fail();
        }

        // ✅ 从配置获取超级管理员角色
        private bool IsSuperAdmin(string roleCode)
        {
            return roleCode.Equals(_superAdminRole, StringComparison.OrdinalIgnoreCase);
        }
    }
}